import cv2
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt


#   对输入图像进行resize
def resize_image(image, size, letterbox_image):
    iw, ih = image.size
    w, h = size
    if letterbox_image:
        scale = min(w / iw, h / ih)
        nw = int(iw * scale)
        nh = int(ih * scale)

        image = image.resize((nw, nh), Image.BICUBIC)
        new_image = Image.new('RGB', size, (128, 128, 128))
        new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))
    else:
        new_image = image.resize((w, h), Image.BICUBIC)
    return new_image


# cv2 to pil
def cv_to_pil(img):
    return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))


# pil to cv2
def pil_to_cv(img):
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


# detect image
def detect_image(image_1, image_2):
    # 计算二者之间的距离
    l1 = np.linalg.norm(image_1 - image_2, axis=1)

    plt.subplot(1, 2, 1)
    plt.imshow(image_1)

    plt.subplot(1, 2, 2)
    plt.imshow(image_2)
    plt.text(-12, -12, 'Distance:%.3f' % l1, ha='center', va='bottom', fontsize=11)
    plt.show()
    return l1


# normalization
def preprocess_input(image):
    image /= 255.0
    return image


# image type transform
def image_transform(img):
    img = cv_to_pil(img)
    img = resize_image(img, [160, 160], letterbox_image=True)
    img = np.expand_dims(preprocess_input(np.transpose(img, [2, 0, 1]).astype(np.float32)), 0)
    return img
